package com.fesnakj.todos.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fesnakj.todos.model.User;
import com.fesnakj.todos.repository.UserRepository;

@Controller
public class UserController {

    @Autowired
    private UserRepository dao;

    @RequestMapping("/users")
    public String getAllUsers(Model model) {
        List<User> allUsers = dao.findAll();
        model.addAttribute("allUsers", allUsers);
        return "users";
    }

    @RequestMapping(value = "/users/add", method = RequestMethod.GET)
    public String showAddUserForm(Model model) {
        User newUser = new User();
        model.addAttribute("newUser", newUser);
        return "addUser";
    }

    @RequestMapping(value = "/users/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("newUser") @Valid User newUser, BindingResult result) {
        if (result.hasErrors()) {
            return "addUser";
        }
        dao.save(newUser);
        return "redirect:/users";
    }

    @RequestMapping(value = "/users/remove")
    public String removeUser(@RequestParam("id") int userId) {
        dao.deleteById(userId);
        return "redirect:/users";
    }

}
